package parser;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/21 11:40
 * Version:1.0-SNAPSHOT
 * Description: 使用递归的方式进行打印操作
 * 在控制台打印xml中的内容
 * 要求控制台输出的内容与xml文件内容完全一致,包括格式
 */
public class PrintDomParser {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(PrintDomParser.class.getClassLoader().getResourceAsStream("students.xml"));
            Element root = document.getDocumentElement();
            print(root);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void print(Element root){
        // 打印开始标签
        System.out.print("<"+root.getTagName());
        // 打印标签属性
        NamedNodeMap attributes = root.getAttributes();
        for(int i = 0; i < attributes.getLength();i ++){
            System.out.print(" "+attributes.item(i));
        }
        System.out.print(">");

        // 打印标签体
        NodeList nodes = root.getChildNodes();
        for(int i = 0; i < nodes.getLength(); i++){
            Node node = nodes.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE){
                Element element = (Element) node;
                print(element);
            }
            if(node.getNodeType() == Node.TEXT_NODE){
                System.out.print(node.getTextContent());
            }
        }


        // 打印结束标签
        System.out.print("<"+root.getTagName()+">");
    }

}
